'use strict';

const Service = require('egg').Service;

class ReceivingAddressService extends Service {
  async selAll(userid) {
    const {
      ctx,
    } = this;
    const result = await ctx.model.Receivingaddress.findAll({
      where: {
        uid: userid,
      },
    });
    const address = [];
    if (result) {
      result.forEach(item => {
        address.push(item.dataValues);
      });
    }
    return address;
  }
  async add(addressInfo) {
    const {
      ctx,
    } = this;
    const result = await ctx.model.Receivingaddress.create({
      consignee: addressInfo.name,
      province: addressInfo.province,
      city: addressInfo.city,
      county: addressInfo.county,
      street: addressInfo.street,
      detailed: addressInfo.detailedAddress,
      tel: addressInfo.tel,
      email: addressInfo.email,
      address_alias: addressInfo.alias,
      default_address: addressInfo.default_address,
      uid: addressInfo.userid,
      createdDate: new Date(),
      updatedDate: new Date(),
    });
    if (result.dataValues) {
      return {
        status: 200,
        data: {
          msg: '增加地址成功',
        },
      };
    }
    return {
      status: 400,
      data: {
        msg: '增加地址失败，请重新输入后再试',
      },
    };
  }
  async upAll_defaultAddress(userid) {
    const {
      ctx,
    } = this;
    console.log(userid);
    const upres = await ctx.model.Receivingaddress.update({
      default_address: false,
    }, {
      where: {
        uid: userid,
      },
    });
    if (upres) {
      return {
        status: 200,
        upres,
      };
    }
    return {
      status: 400,
    };
  }
  async upAddress(upAddressInfo) {
    const { ctx } = this;
    const result = await ctx.model.Receivingaddress.update(
      {
        consignee: upAddressInfo.name,
        province: upAddressInfo.province,
        city: upAddressInfo.city,
        county: upAddressInfo.county,
        street: upAddressInfo.street,
        detailed: upAddressInfo.detailedAddress,
        tel: upAddressInfo.tel,
        email: upAddressInfo.email,
        address_alias: upAddressInfo.alias,
        default_address: upAddressInfo.default_address,
        uid: upAddressInfo.userid,
        updatedDate: new Date(),
      },
      {
        where: {
          id: upAddressInfo.id,
        },
      }
    );
    if (result) {
      return {
        status: 200,
        data: {
          msg: '修改收货地址成功',
        },
      };
    }
    return {
      status: 400,
      data: {
        msg: '修改收货地址失败，请重新再试',
      },
    };
  }
}

module.exports = ReceivingAddressService;
